package org.zebias.udpnettydemo.server;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

import java.util.concurrent.ThreadLocalRandom;

/**
 * @ClassName UdpServerHandler
 * @Description 服务端处理类
 * @Author zebias
 * @Date 2021/3/1 16:52
 * @Version 1.0
 **/
public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    public static final String [] DICTIONARY = {"测试","测试","测试","测试","测试","测试"};

    private String nextQuote() {
        //线程安全基类，避免多线程环境发生错误
        int quote = ThreadLocalRandom.current().nextInt(DICTIONARY.length);
        return DICTIONARY[quote];
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        // 利用ByteBuf的toString方法获取请求信息
        String info = msg.content().toString(CharsetUtil.UTF_8);
        System.out.println(info);
        ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("我收到了", CharsetUtil.UTF_8), msg.sender()));
    }
}
